/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool find(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        if(!root)
            return false;
        if(root->val == p->val || root->val == q->val)
            return true;
        else
            return find(root->left, p, q) || find(root->right, p, q);
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root)
            return root;
        if(root->val == p->val || root->val == q->val)
            return root;
        bool findp = find(root->left, p,q);
        bool findq = find(root->right, p,q);
        if(findp && findq)
            return root;
        else if(findp && !findq)
            return lowestCommonAncestor(root->left, p, q);
        else if(!findp && findq)
            return lowestCommonAncestor(root->right, p, q);
        else
            return NULL;
    }
};

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || root == p || root == q)
            return root;

        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);

        if(left == NULL && right == NULL)
            return NULL;
        else if(left && right)
            return root;
        else
            return !left ? right : left;
        
    }
};